<template>
  <div class="login_container">
    <!-- 登录盒子  -->
    <div class="login_box">
      <!-- 头像 -->
      <div class="avatar_box">
        <img src="../assets/image/登录头像4.png" alt="">
      </div>
      <!-- 登录表单 -->
      <el-form :model="loginForm" ref="LoginFormRef" :rules="loginFormRules" label-width="0px" class="login_form">
        <!-- 用户名 -->
        <el-form-item prop="userName" style="margin-top: 50px;">
          <el-input v-model="loginForm.userName" prefix-icon="iconfont icon-user"
                    placeholder="请输入用户名"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password" style="">
          <el-input type="password" v-model="loginForm.password"
                    prefix-icon="iconfont icon-pwd" placeholder="请输入密码"></el-input>
        </el-form-item>

        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>

        <!-- 验证码 -->
         <!-- Element UI 的弹出框组件
          placement="bottom"	弹出框出现在触发按钮的下方
          trigger="click"	点击按钮时触发弹出框（默认是 hover）
          ref="close"	用于在代码中通过 this.$refs.close 控制弹出框（如关闭）
         -->
        <el-popover
            placement="bottom"
            width="335"
            trigger="click"
            ref="close">
            <!-- 滑动验证组件 -->
          <slide-verify :l="42"
                        :r="10"
                        :w="310"
                        :h="155"
                        slider-text="向右滑动"
                        @success="onSuccess"
                        @fail="onFail"
                        @refresh="onRefresh"
                        @fulfilled="onFulfilled"
                        :accuracy="accuracy"
                        ref="slideblock"
          ></slide-verify>
          <div>{{msg}}</div>
          <!-- 按钮 -->
          <el-button type="primary" slot="reference" class="btn-login">登录</el-button>
          <el-button type="info" slot="reference" @click="resetLoginForm" class="btn-reset">重置</el-button>
        </el-popover>

      </el-form>
    </div>
  </div>
</template>


<script>

export default {
  data() {
    return {
      codeUrl: "",
      //数据绑定
      loginForm: {
        userName: '',
        password: '',
        rememberMe: false,
      },
      //表单验证规则
      loginFormRules: {
        userName: [
          {required: true, message: "请输入登录名", trigger: "blur"},
          {min: 3, max: 10, message: "登录名长度在3-10个字符", trigger: "blur"}
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {min: 6, max: 16, message: "密码长度在6-16个字符", trigger: "blur"}
        ],

      },
      //验证码
      msg: '',
      // 精确度小，可允许的误差范围小；为1时，则表示滑块要与凹槽完全重叠，才能验证成功。默认值为5
      accuracy: 3,
    }
  },

  // 7天免登录
  mounted: function() {
    this.getCookie();//调用函数
    //取出保存的状态记住密码
    if(localStorage.getItem('checked')=='false'){
      this.loginForm.rememberMe = false
    }else if(localStorage.getItem('checked')=='true'){
      // this.checked=true
      this.loginForm.rememberMe = true
    }
  },

  methods: {
    //验证码
    onSuccess(times){
      // 1 关闭弹出层
      this.$refs.close.doClose()
      // 2. 重置滑块状态
      this.$refs.slideblock.refresh()
      // 3. 显示成功提示
      this.$message.success('验证通过，耗时' + (times / 1000).toFixed(1) + 's')
      // 4. 记录验证耗时信息
      this.msg = '验证通过，耗时' + (times / 1000).toFixed(1) + 's'
      this.login()
    },
    onFail(){
      this.$message.error('验证不通过')
      this.msg = ''
    },
    onRefresh(){
      this.msg = ''
    },
    onFulfilled() {
      this.$message.success('刷新成功')
    },
    //添加表单重置方法
    resetLoginForm() {
      //this=>当前组件对象，其中的属性$refs包含了设置的表单ref
      this.loginForm = {
        userName: 'test',
        password: '123456'
      }
    },
    //7天免登录
    //设置cookie
    setCookie(c_name, c_pwd, exdays) {
      var exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      //字符串拼接cookie
      window.document.cookie = "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie = "password" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
    },
    //读取cookie
    getCookie: function() {
      if (document.cookie.length > 0) {
        //显示的格式需要切割
        var arr = document.cookie.split('; ');
        for (var i = 0; i < arr.length; i++) {
          //再次切割
          var arr2 = arr[i].split('=');
          //判断查找相对应的值
          if (arr2[0] == 'userName') {
            //保存到保存数据的地方
            this.loginForm.userName = arr2[1];
          } else if (arr2[0] == 'password') {
            this.loginForm.password = arr2[1];
          }
        }
        this.checked = true;
      }
    },
    //清除cookie
    clearCookie: function () {
      this.setCookie("", "", -1); //修改2值都为空，天数为负1天就好了
    },
    //登录
    login() {
      // this.$message.success('执行了登录方法')
      //点击登录的时候先调用validate方法验证表单内容是否有误
      // console.log(res)
      // .validate()	Element UI 表单的内置方法，触发全部表单项的校验规则
      this.$refs.LoginFormRef.validate(valid => {
        console.log("login-》校验规则=", this.loginFormRules);
        //如果valid参数为true则验证通过
        if (!valid) {
          return
        }
      })

      //发送请求进行登录
      // const { data: res }	解构赋值：从响应对象中提取 data 并重命名为 res
      const res = this.$http.post('sys/login', this.loginForm)
          .then((res) => {
            console.log("login-res成功·->" + res);
            // console.log("login-res成功·->"+Sty);
            this.$message.success('登录成功')
            //把点击记住存到本地去
            console.log("本地存储=", this.loginForm.rememberMe)
            localStorage.setItem('checked', this.loginForm.rememberMe ? 'true' : 'false')
            //判断复选框是否被勾选 勾选则调用配置cookie方法
            if (this.loginForm.rememberMe == true) {
              //传入账号名，密码，和保存天数3个参数
              this.setCookie(this.loginForm.userName, this.loginForm.password, 365);
            } else {
              console.log("清空Cookie");
              //清空Cookie
              this.clearCookie();
            }

            // console.log(res)
            // 数据仅在当前浏览器标签页有效，关闭标签页后自动清除 可用约为5MB
            window.sessionStorage.setItem('userId', res.data.data.userId)
            //保存token
            window.sessionStorage.setItem('token', res.data.token)
            //存头像
            window.sessionStorage.setItem('avatar', res.data.data.avatar)
            // 导航至/home
            this.$router.push('/home')
          })
          .catch((res) => {
            // res=JSON.stringify(res)
            console.log("login-res失败->" + res);
            this.$message.error('登录失败:' + res.msg) //console.log("登录失败:"+res.meta.msg)
          })

    },

  },
  components: {},
}
</script>
<!-- 
lang="less":支持变量、嵌套、混入（Mixins）、运算等高级功能。
scoped: 功能：限定样式仅作用于当前组件，避免全局污染。
-->
<style lang="less" scoped>

.login_container {
  background-image: url("../assets/image/智慧社区壁纸2.jpg");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: center;
  top: 0;
  left: 0;
  width: 100%;
  min-width: 1080px;
  height: 100%;
}

.login_box {
  width: 440px;
  height: 300px;
  background: #fff;
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  //整个登录表单透明
  //opacity: 0.9;
  //局部透明
  background: rgba(255, 255, 255, .6);

  .avatar_box {
    height: 130px;
    width: 130px;
    border: 1px solid #eee;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 0 10px #ddd;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;

    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eee;
    }
  }
}

.login_form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}

.btns {
  //display: flex;
  //justify-content: flex-end;
  //border: 1px solid black;
}

.btn-login {
  width: 100px;
  margin: auto 45px auto 50px;
}

.btn-reset {
  width: 100px;
}
</style>
